import { Button } from "antd";
import {
  FC,
  ReactElement,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";
import { sendMailCode } from "../../../api/authApi";
import { useAuth } from "../../../api/AuthContext";
import { Mask, Wrap } from "./UpdateUsername";

interface IProps {}

const BindEMail: FC<IProps> = (): ReactElement => {
  const { auth, verificationMailCode } = useAuth();
  const mail = useRef<HTMLInputElement>(null);
  const codeRef = useRef<HTMLInputElement>(null);
  const [showConfirmInput, setShowConfirmInput] = useState(false);
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(60);
  const [againSending, setAgainSending] = useState(false);
  const [encryptedInfo, setEncryptedInfo] = useState("");
  const countdownTimer = useRef<any>(0);

  const decreaseCountdown = useCallback(() => {
    countdownTimer.current = setTimeout(() => {
      setCountdown(count => {
        if (count > 1) decreaseCountdown();
        return count - 1;
      });
    }, 1000);
  }, []);

  useEffect(() => {
    if (showConfirmInput) decreaseCountdown();
    else clearTimeout(countdownTimer.current);
  }, [decreaseCountdown, showConfirmInput]);

  const verification = async () => {
    const code = codeRef.current?.value;
    if (!code) return;
    const result = await verificationMailCode({ code, encryptedInfo });
    if (result) {
      setShowConfirmInput(false);
    }
  };

  const sendMailCodeAgain = useCallback(() => {
    setAgainSending(true);
    sendMailCode(mail.current!.value).then(msg => {
      setAgainSending(false);
      if (msg) {
        //开启新的倒计时
        setCountdown(60);
        setEncryptedInfo(msg);
        decreaseCountdown();
      }
    });
  }, [decreaseCountdown]);

  const handleSendMailCode = () => {
    const email = mail.current?.value;
    if (email) {
      setLoading(true);
      sendMailCode(email).then(msg => {
        setLoading(false);
        if (msg) {
          setShowConfirmInput(true);
          setEncryptedInfo(msg);
        }
      });
    }
  };

  const cancelVerification = () => setShowConfirmInput(false);

  if (auth.mail) {
    return (
      <Wrap>
        已绑定邮箱: <strong>{auth.mail}</strong>
      </Wrap>
    );
  }

  return (
    <Wrap>
      <input ref={mail} type='text' placeholder='邮箱地址' />
      <Button type='primary' loading={loading} onClick={handleSendMailCode}>
        确定
      </Button>
      <Mask show={showConfirmInput}>
        <input ref={codeRef} type='text' placeholder='输入验证码以确定' />
        <div>
          <Button type='ghost' onClick={cancelVerification}>
            取消
          </Button>

          <Button type='primary' onClick={verification} loading={loading}>
            确定
          </Button>
          <Button
            type='link'
            disabled={!!countdown}
            onClick={sendMailCodeAgain}
            loading={againSending}
          >
            {countdown ? countdown + "s" : ""} 再发一次
          </Button>
        </div>
      </Mask>
    </Wrap>
  );
};

export default BindEMail;
